package cn.cool.netty.nio.buffer;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class TestByteBuffer {
    public static void main(String[] args) throws FileNotFoundException {
        try (FileChannel channel = new FileInputStream("E:\\java\\code_learn\\netty-learn\\src\\main\\java\\cn\\cool\\netty\\data.txt").getChannel()) {
            ByteBuffer buffer = ByteBuffer.allocate(10);
            while (true) {
                // read表示读取到的字节数量，-1表示数据已经从channel读取完成
                int read = channel.read(buffer);
                System.out.println(read);
                if (read == -1) break;
                // 切换到读模式
                buffer.flip();
                while (buffer.hasRemaining()) {
                    System.out.print((char) buffer.get());
                }
                System.out.println();
                // 切换到写模式
                buffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
